<template>
  <div>
    <span>城市：</span>
    <select v-model="ct">
      <option>请选择</option>
      <option :value="item.name" v-for="item in city" :key="item.id">
        {{ item.name }}
      </option>
    </select>
    <div>用户名：<input type="text" v-model="name" /></div>
    <div>年龄：<input type="text" v-model="age" /></div>
    <button @click="add">提交</button>
  </div>
</template>

<script>
import Bus from "../Bus";
export default {
  props: ["list"],
  data() {
    return {
      city: [
        { id: 1, name: "武威" },
        { id: 2, name: "秦皇岛" },
        { id: 3, name: "北京" },
        { id: 4, name: "太原" },
        { id: 5, name: "哈尔滨" },
      ],
      name: "",
      age: "",
      ct: "",
      show: false,
      key: 0
    }
  },
  methods: {
    add() {
      if (this.show) {
        if (this.name == "" || this.age == "" || this.ct == "") {
          return alert("内容不能为空");
        }
        let obj = {
          name: this.name,
          age: this.age,
          city: this.ct,
          flag: false,
        };
        this.$emit("add", obj);
        this.name = this.age = this.ct = "";
      } else {
        this.list[this.key].name = this.name;
        this.list[this.key].age = this.age;
        this.list[this.key].city = this.ct;
        this.show = true;
      }
    },
  },
  mounted() {
    Bus.$on("edit", (k) => {
      this.key = k;
      this.name = this.list[k].name;
      this.age = this.list[k].age;
      this.ct = this.list[k].city;
      this.show = false
    });
  },
};
</script>

